{extend name="iframe" /}
{block name="css"}
    <style type="text/css">
        body{
            background: #f1f1f1;
        }
        .content-wrapper-box{
            padding: 10px;
        }
        .content-wrapper{
            padding: 10px 16px;
            background: #ffffff;
            border: 1px solid #ececec;

        }
        .opt_btn{
            margin-left: 10px;
        }
        #searchForm{
            margin-top: 0;
        }
        .form-group{
            margin-top:10px;
        }
        .control-label{
            font-size: 14px;
            font-weight: normal;
            padding: 0;
            padding-top: 7px;
            text-align: right;
        }
        .table_image{
            height:30px;
            width:auto;
            display: block;
        }
        .bootstrap-table td.bs-checkbox{
            vertical-align: middle;
        }
        .bootstrap-table td.bs-checkbox > input{
            margin-top: 4px !important;
        }
    </style>
{/block}

{block name="content"}
    <div class="container-fluid content-wrapper-box">
        <div class="content-wrapper">
            <!-- 搜索表单 -->
            <form id="searchForm" class="form-inline row" action="" method="get">
                 <div class="form-group col-xs-12 col-sm-6 col-md-4 col-lg-3">
                    <label class="control-label col-xs-4">
                        商家名称&nbsp;
                    </label>
                    <div class="col-xs-8">
                        <input type="text" name="name" data-where="like" class="form-control" placeholder="商家名称">
                    </div>
                </div>
                <div class="form-group col-xs-12 col-sm-6 col-md-4 col-lg-3">
                    <label class="control-label col-xs-4">
                        联系人&nbsp;
                    </label>
                    <div class="col-xs-8">
                        <input type="text" name="contact_person" data-where="like" class="form-control" placeholder="联系人">
                    </div>
                </div>
                <div class="form-group col-xs-12 col-sm-6 col-md-4 col-lg-3">
                    <label class="control-label col-xs-4">
                        联系电话&nbsp;
                    </label>
                    <div class="col-xs-8">
                        <input type="text" name="contact_phone" data-where="like" class="form-control" placeholder="联系电话">
                    </div>
                </div>
                <div class="form-group col-xs-12 col-sm-6 col-md-4 col-lg-3">
                    <label class="control-label col-xs-4">
                        状态&nbsp;
                    </label>
                    <div class="col-xs-8">
                        <select class="form-control" name="status" data-where="eq">
                            <option value="">请选择</option>
                            <option value="1">是</option>
                            <option value="2">否</option>
                        </select>
                    </div>
                </div>

                <div class="form-group col-xs-12">
                    <!--【省市区】-->
                    <div class="row">
                        <div class="col-xs-12 col-sm-8 col-md-8 col-lg-6">
                            <label class="control-label col-xs-2">
                                所在地区&nbsp;
                            </label>
                            <div class="col-xs-8" id="cxselect_addr">
                                <select class="province form-control" name="mch_province" data-where="eq" data-first-title="选择省"></select>
                                <select class="city form-control" name="mch_city" data-where="eq" data-first-title="选择市"></select>
                                <!--<select class="area form-control" name="area" data-first-title="选择区"></select>-->
                            </div>
                        </div>
                        <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
                            <div class="col-xs-2"></div>
                            <div class="col-xs-8">
                                <button class="btn btn-primary" onclick="searchForm()" type="button">搜索</button>
                                <button class="btn btn-default" type="button" onclick="resetForm()">重置</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <!-- 工具条 -->
            <div id="toolbar">
                <button class="btn btn-primary btn-sm" onclick="add()"><i class="fa fa-plus"></i> 添加</button>
                <button class="btn btn-info btn-sm" id="edit_btn" disabled onclick="editMut()"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger btn-sm" id="delete_btn" disabled onclick="deleteMut()"><i class="fa fa-trash"></i> 删除</button>
            </div>
            <!-- 表格 -->
            <table id="table" class="table-bordered"></table>
        </div>
    </div>
{/block}

{block name="script"}
<script type="text/javascript" charset="utf-8" src="__STATIC__/plugins/cxselect/jquery.cxselect.min.js"> </script>
    <script type="text/javascript">
        //注册switch 开关转换事件
        function statusFormatter(field,value,row,index) {
            var id = row.id;
            if(value===1){
                return '<input value="'+ id +'" data-field="'+ field +'" type="checkbox" class="switch" checked>';
            }
            else if(value===2){
                return '<input value="'+ id +'" data-field="'+ field +'" type="checkbox" class="switch" >';
            }
        }

        //注册时间戳类型转换事件
        function timeFormatter(field,value,row,index) {
            if(row[field]===null || row[field]===0) {
                return '';
            }else if(row[field]!==''){
                return  moment(row[field]*1000).format('YYYY-MM-DD HH:mm:ss');
            }else{
                return '';
            }
        }

        //注册商家服务按钮事件
        function mchSrvFormatter(value, row, index) {
            var $arr = [
                '<a id="srv_item" type="button" class="btn btn-info btn-xs opt_btn"><i class="fa fa-edit"></i>服务项目</a>',
                '<a id="srv_overarea" type="button" class="btn btn-default btn-xs opt_btn"><i class="fa fa-edit"></i>服务范围</a>',
            ];
            return $arr.join('');
        }
        //按钮事件
        window.mchSrvEvents = {
            //编辑一行数据
            'click #srv_item': function(e, value, row, index) {
                e.stopPropagation();
                handleSrvItem(row.id);
            },
            'click #srv_overarea': function(e, value, row, index) {
                e.stopPropagation();
                handleMchOverarea(row.id);

            },
        };

        //注册操作按钮事件
        function operateFormatter(value, row, index) {
            var $arr = [
                '<button id="edit_row" type="button" class="btn btn-info btn-xs opt_btn" title="编辑"><i class="fa fa-edit"></i></button>',
            ];
                $arr.push('<button id="delete_row" type="button" class="btn btn-danger btn-xs opt_btn" title="删除"><i class="fa fa-trash"></i></button>');
            return $arr.join('');
        }
        //按钮事件
        window.operateEvents = {
            //编辑一行数据
            'click #edit_row': function(e, value, row, index) {
                e.stopPropagation();
                handleEdit(row.id);
            },
            'click #delete_row': function(e, value, row, index) {
                layer.confirm('您确认要删除所选记录吗?', {icon: 3, title:'提示'}, function(index){
                    handleDelete([row.id]);
                    layer.close(index);
                });

            },
        };
        //表格数据组装
        var fieldList = [
            {
            valign:"middle",field:"id",title:"编号"
            },
            {
            valign:"middle",field:"name",title:"商家名称"
            },
            {
            valign:"middle",field:"contact_person",title:"联系人"
            },
            {
                valign:"middle",field:"contact_phone",title:"联系电话",formatter:function (value,row,index){
                    var content = '';
                    $.each(value, function (idx,phone) {
                        if(phone=='') return false;
                        var callTag = '<a href="javascript:;" class="text-info clkcall" title="点击呼叫"><i class="fa fa-phone-square" style="font-size:18px;"></i></a>&nbsp;&nbsp;';
                        content += callTag + '<span>' + phone +'</span><br>';
                    });
                    return content;
                }
            },
            {
            valign:"middle",field:"mch_province",title:"商家所在地区", formatter:function (value,row,index){
                    return row.mch_province +' ' + row.mch_city +' ' + row.mch_area;
                }
            },
            {
            valign:"middle",field:"mch_addr",title:"详细地址", visible:false
            },
            {
            valign:"middle",field:"add_time",title:"创建时间", visible:false,formatter:function (value,row,index){return timeFormatter('add_time',value,row,index);}
            },
            {
                valign:"middle",field:"brief",title:"简介", visible:false
            },
            {
                valign:"middle",field:"status",title:"启用状态",formatter:function (value,row,index){return statusFormatter('status',value,row,index);}
            }];
        var columns = [{
            align: 'center',
            valign: 'middle',
            checkbox: 'true'
        }].concat(fieldList).concat(
            [{
                field: 'merchant_service',
                title: '商家服务',
                align: 'center',
                valign: 'middle',
                events: mchSrvEvents,
                formatter: mchSrvFormatter
            },{
                field: 'operate',
                title: '操作',
                align: 'center',
                valign: 'middle',
                events: operateEvents,
                formatter: operateFormatter
            }]
        );

        //ajax改变状态
        function changeState(id,field,value) {
            $.ajax({
                url:'{:url("Merchant/changeState")}',
                type:'post',
                dataType:'json',
                data:{id:id,field:field,value:value},
                success:function (response) {
                    if(response.code === 0){
                        toastr.success(response.msg);
                    }else{
                        toastr.error(response.msg);
                    }
                },
                error:function (e) {
                    toastr.error("network error!");
                }
            });
        }


        /**
         * 表单搜索提交
         */
        function searchForm() {
            $("#table").bootstrapTable('destroy');
            oTableInit();
        }

        /**
         * 重置表单
         */
        function resetForm() {
            $('#searchForm')[0].reset();
            $("#searchForm select").val("").trigger('change');
            searchForm();
        }

        /**
         * 工具条 添加操作
         */
        function add () {
            var area = [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 520 ? '520px' : '95%'];
            layer.open({
                type: 2,
                title: '添加',
                maxmin: true,
                scrollbar:false,
                anim:0,
                shade:0,//隐藏遮罩层
                area : area,
                content: '{:url("Merchant/add")}',
                btn:['确定','重置'],
                btnAlign:'c',
                yes:function (index,layero) {
                    var iframe = layero.find("iframe")[0].contentWindow.document;
                    $(iframe).find('.submit_btn').click();
                },
                btn2:function (index,layero) {
                    var iframe = layero.find("iframe")[0].contentWindow.document;
                    $(iframe).find('.reset_btn').click();
                    return false;
                }
            });
        }

        /**
         * 工具条 编辑多个操作
         */
        function editMut() {
            var rows = $('#table').bootstrapTable('getSelections');
            $.each(rows,function (index,value) {
                handleEdit(value.id);
            });
        }

        /**
         * 工具条 删除多个操作
         */
        function deleteMut() {
            var rows = $('#table').bootstrapTable('getSelections');
            var ids = [];
            $.each(rows,function (index,value) {
                ids.push(value.id);
            });

            layer.confirm('您确认要删除所选记录吗?', {icon: 3, title:'提示'}, function(index){
                handleDelete(ids);
                layer.close(index);
            });
        }

        /**
         * 编辑商家服务项目
         */
        function handleSrvItem(id){
            var area = [$(window).width() > 800 ? '800px' : '85%', $(window).height() > 520 ? '480px' : '95%'];
            layer.open({
                type: 2,
                title: '编辑商家(编号: '+ id +')的服务项目',
                maxmin: true,
                scrollbar:false,
                anim:0,
                shade:0,//隐藏遮罩层
                area : area,
                content: '{:url("Merchant/SrvItem")}?id=' + id,
                btn:['保存','取消'],
                btnAlign:'c',
                yes:function (index,layero) {
                    var iframe = layero.find("iframe")[0].contentWindow.document;
                    $(iframe).find('.submit_btn').click();
                },
                btn2:function (index,layero) {
                    layer.close(index);
                }
            });
        }

        /**
         * 编辑商家服务区域范围
         */
        function handleMchOverarea(id){
            var area = [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 520 ? '520px' : '95%'];
            layer.open({
                type: 2,
                title: '编辑商家(编号: '+ id +')的覆盖区域',
                maxmin: true,
                scrollbar:false,
                anim:0,
                shade:0,//隐藏遮罩层
                area : area,
                content: '{:url("Merchant/overarea")}?id=' + id,
                btn:['保存','取消'],
                btnAlign:'c',
                yes:function (index,layero) {
                    var iframe = layero.find("iframe")[0].contentWindow.document;
                    $(iframe).find('.submit_btn').click();
                },
                btn2:function (index,layero) {
                    layer.close(index);
                }
            });
        }

        /**
         * 执行编辑操作
         */
        function handleEdit(id){
            var area = [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 520 ? '520px' : '95%'];
            layer.open({
                type: 2,
                title: '编辑',
                maxmin: true,
                scrollbar:false,
                anim:0,
                shade:0,//隐藏遮罩层
                area : area,
                content: '{:url("Merchant/edit")}?id=' + id,
                btn:['保存','取消'],
                btnAlign:'c',
                yes:function (index,layero) {
                    var iframe = layero.find("iframe")[0].contentWindow.document;
                    $(iframe).find('.submit_btn').click();
                },
                btn2:function (index,layero) {
                    layer.close(index);
                }
            });
        }

        /**
         * 执行删除操作
         */
        function handleDelete(ids) {
            $.ajax({
                //url:'{:url("Merchant/delete")}',
                url:'{:url("Merchant/softDel")}',
                type:'post',
                dataType:'json',
                data:{ids:ids},
                success:function (response) {
                    if(response.code === 0){
                        //searchForm();
                        $("#table").bootstrapTable('refresh');
                        toastr.success(response.msg);
                    }else{
                        toastr.error(response.msg);
                    }
                },
                error:function (e) {
                    toastr.error("network error!");
                }
            });
        }

        /**
         * 改变按钮状态
         */
        function toggleToolBtn() {
            var rows = $('#table').bootstrapTable('getSelections');
            if(rows.length > 0){
                //激活
                $('#edit_btn').removeAttr('disabled');
                $('#delete_btn').removeAttr('disabled');
            }else {
                //禁用
                $('#edit_btn').attr('disabled', true);
                $('#delete_btn').attr('disabled', true);
            }
        }


        /**
         * 初始化表格
         */
        function oTableInit() {
            $('#table').bootstrapTable({
                url:'{:url("Merchant/index")}',
                dataUndefinedText:'-',         //当数据为 undefined 时显示的字符。
                dataStriped:true,               //隔行变色
                dataSortName:'',                //排序列，通过url方式获取数据填写字段名，否则填写下标
                dataSortOrder:'asc',            //升序
                dataType:'json',                //ajax返回类型
                ajaxOptions:{},                 //ajax附加项
                queryParamsType : "undefined",  //查询类型
                queryParams:function (params) {
                    var param = {
                        page: params.pageNumber,
                        pageSize: params.pageSize,
                        query:{},
                        op:{}
                    };

                    $.each($('#searchForm').serializeArray(),function (index,val) {
                        if(val.value!==null && val.value !==""){
                            param['query'][val.name] = val.value;
                            param['op'][val.name] = $('[name="'+ val.name +'"]').attr('data-where');
                        }
                    });

                    return param;

                }, //查询参数
                striped: true, //表格显示条纹
                iconSize: 'sm',//按钮控件大小
                pagination:true,                //分页条
                onlyInfoPagination:false,       //仅显示总记录数
                sidePagination:'server',        //服务端分页
                pageSize:{$Think.config.sys_param.pagesize|default=10},                    //每页显示记录数
                pageList:[10, 25, 50, 100],     //分页页数选择
                paginationHAlign:'right',       //分页条位置
                paginationPreText:'上一页',      //上一页
                paginationNextText:'下一页',     //下一页
                columns: columns,
                search:false,//禁用默认搜索太LOW
                showRefresh:true,//刷新按钮
                showColumns:true,//列筛选按钮
                showToggle:false,//切换视图
                buttonsAlign:'right',//工具栏按钮的位置
                uniqueId:'id',//主键
                clickToSelect:true,//选中此行的checkbox或radio
                singleSelect:false,//复选框仅能选中一行
                checkboxHeader:true,//显示全选
                toolbar:'#toolbar',//按钮工具条
                onLoadSuccess:function(){
                    var switch_obj = $('.switch'),i=0;

                    switch_obj.bootstrapSwitch({
                        onText:"<i class='fa fa-check'></i>",
                        offText:"<i class='fa fa-close'></i>",
                        onColor:"success",
                        offColor:"danger",
                        //size:"small",//无效
                        onSwitchChange:function(event,state){
                            if(state===true){
                                changeState(this.value,$(this).attr('data-field'),1);
                            }else{
                                changeState(this.value,$(this).attr('data-field'),2);
                            }
                        }
                    });
                    switch_obj.bootstrapSwitch('size','mini');
                    for(;i < switch_obj.length;i++){
                        if(switch_obj.eq(i).is(":checked")){
                            switch_obj.eq(i).bootstrapSwitch('state',true);
                        }else{
                            switch_obj.eq(i).bootstrapSwitch('state',false);
                        }

                    }

                },
                onCheck:function (row) {
                    toggleToolBtn();
                },
                onUncheck:function (row) {
                    toggleToolBtn();
                },
                onCheckAll:function (rows) {
                    toggleToolBtn();
                },
                onUncheckAll:function (rows) {
                    toggleToolBtn();
                }
            });
        }

        $(function () {
            //初始化表格
            oTableInit();

            $('#cxselect_addr').cxSelect({
                url: '/public/admin/plugins/cxselect/cityData.min.json',
                //selects: ['province', 'city', 'area'],
                selects: ['province', 'city'],
                emptyStyle: 'none'
            });


            //点击拨号
            $('#table').on("click", 'a.clkcall' ,function() {
                var callee_phone = $(this).next('span').text();
                if(callee_phone==''){
                    bootbox.error('呼叫失败：号码不能为空！');
                    return;
                }
                top.clickcall(callee_phone);
                return false;
            });
        });
    </script>
{/block}
